package com.tangtang.register.client;

import com.alibaba.fastjson.JSONObject;

import java.util.UUID;

public class RegisterClient {
    private   String serviceInstanceId;
    public RegisterClient(){
        serviceInstanceId = UUID.randomUUID().toString().replace("-", "");
    }

    public void start(){
        RegisterWorker registerWorker = new RegisterWorker(serviceInstanceId);

        registerWorker.start();
        registerWorker.setDaemon(true);
    }

    private class RegisterWorker extends Thread {
        private HttpSender httpSender = null;

        private volatile Boolean finshedRegister;
        private String serviceInstanceId;

        public RegisterWorker(String serviceInstanceId) {
            this.httpSender = new HttpSender();
            this.finshedRegister = false;
            this.serviceInstanceId = serviceInstanceId;
        }


        @Override
        public void run() {
            String serverName = "product-server";
            if (!finshedRegister) {
                RegisterRequest request = new RegisterRequest();
                request.setHostName("product01");
                request.setIp("192.168.0.1");
                request.setPort(8081);

                request.setServerName(serverName);
                request.setServiceInstenceId(this.serviceInstanceId);
                RegisterResponse response = httpSender.register(request);

                System.out.println("服务注册结果【+" + JSONObject.toJSONString(response) + "】");
                if (response.getStatus().equals(RegisterResponse.SUCCESS)) {
                    finshedRegister = true;
                } else {
                    return;
                }
            }

            if(finshedRegister){
                HeartbeatRequest request = new HeartbeatRequest();
               request.setServiceName(serverName);
                request.setServiceInstanceId(this.serviceInstanceId);
                HeartbeatRespnce heartbeatRespnce = httpSender.heartBeat(request);

                while (finshedRegister) {
                    System.out.println("对服务实例【+" + serviceInstanceId + "+】发送心跳检测结果，" + JSONObject.toJSONString(heartbeatRespnce));
                    try {
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
